<?php


namespace app\index\service;


use app\index\model\Coupon;
use app\index\model\IntegralRecord;
use app\index\model\Order;
use app\index\model\RechargeRecord;
use app\index\model\NewKidGiftConfig AS model;
use app\index\model\NewKidGift AS receive;
use app\index\model\UserCash;
use app\index\model\UserCoupon;
use think\Exception;
use think\facade\Db;

class NewKidGiftService
{
    private $mid,$user,$baseIn;
    public function __construct(){
        global $mid,$user,$baseIn;
        $this->mid = $mid;
        $this->user = $user;
        $this->baseIn = $baseIn;
    }

    public function read() : array{
        $data = model::where('start_time','<',now())
            ->where('mall_id',$this->mid)
            ->where('end_time','>',now())
            ->where('status',1)
            ->find();
        if (empty($data))return [HTTP_SUCCESS,[]];
        $data = $data->append(['coupon_data']);
        $config = $data['config'];
        if (empty($config['platform'][$this->baseIn]))return [HTTP_SUCCESS,[]];
        $count = receive::where('user_id',$this->user['id'])
            ->where('mall_id',$this->mid)
            ->where('new_kid_gift_id',$data->id)
            ->count();
        if ($count > 0)return [HTTP_SUCCESS,[]];
        return [HTTP_SUCCESS,$data];
    }

    public function receive(int $id) : array{
        $newkid = model::find($id);
        if (empty($newkid))
            throw new Exception('活动不存在',HTTP_INVALID);
        if ($newkid->start_time > now())
            throw new Exception('活动未开始',HTTP_INVALID);
        if ($newkid->end_time < now())
            throw new Exception('活动已结束',HTTP_INVALID);
        $count = receive::where('user_id',$this->user['id'])
            ->where('new_kid_gift_id',$newkid->id)
            ->count();
        if ($count > 0)
            throw new Exception('您已经领取过了',HTTP_INVALID);
        $config = (object)$newkid->config;
        $cash = UserCash::where('user_id',$this->user['id'])->lock(true)->find();
        $cash->save([
            'total' => $cash->total + $config->amount,
            'integral_total' => $cash->integral_total + $config->integral,
            'integral' => $cash->integral + $config->integral,
            'update_time' => now()
        ]);
        receive::create([
            'user_id' => $this->user['id'],
            'mall_id' => $this->user['mall_id'],
            'new_kid_gift_id' => $id,
            'amount' => $config->amount,
            'integral' => $config->integral,
            'coupon_list' => json_encode($config->coupon)
        ]);
        if (!empty($config->amount))
            RechargeRecord::create([
                'mall_id' => $this->user['mall_id'],
                'user_id' => $this->user['id'],
                'base_in' => $this->baseIn,
                'source_type' => 8,
                'source' => '领取新人礼物',
                'is_online' => 0,
                'type' => 0,
                'money' => $config->amount,
                'service_charge' => 0,
                'remark' => '领取新人礼物余额增加'.$config->amount.'积分增加'.$config->integral.'优惠券领取'.'('.$this->coupon_list((array)$config->coupon).')',
                'trade' => md5(uniqid().rand(1000,9999)),
                'pay_no' => '',
                'status' => 1,
                'create_time' => now(),
                'update_time' => now(),
                'new_cash' => $cash->total - $config->amount,
                'old_cash' => $cash->total
            ]);
        if (!empty($config->integral))
            IntegralRecord::create([
                'mall_id' => $this->user['mall_id'],
                'user_id' => $this->user['id'],
                'status' => 1,
                'integral' => $config->integral,
                'type' => 7,
                'create_time' => now(),
                'update_time' => now()
            ]);
        if (!empty($config->coupon)) {
            foreach ($config->coupon AS $key => $value)
                $coupon[] = [
                    'mall_id' => $this->user['mall_id'],
                    'user_id' => $this->user['id'],
                    'coupon_id' => $value,
                    'merchant_id' => Coupon::where('id',$value)->value('merchant_id'),
                    'type' => 1,
                    'status' => 0,
                    'create_time' => now(),
                    'update_time' => now()
                ];
            if (!empty($coupon))UserCoupon::insertAll($coupon);
        }
        return [HTTP_SUCCESS,UserCash::where('user_id',$this->user['id'])->find()];
    }

    public function coupon_list(?array $coupon) : string{
        $list = Coupon::field('name')
            ->where('id','IN',$coupon)
            ->select()
            ->toArray();
        $name = array_column($list,'name');
        return implode(',',$name);
    }
}